package com.alennus.blog.controller;

import com.alennus.blog.config.shiro.ShiroUtils;
import com.alennus.blog.dto.AccountDto;
import com.alennus.blog.response.WebApiResponse;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * Created by pactera on 2018/5/16.
 */
@RestController
public class LoginController {


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public WebApiResponse login(AccountDto accountDto)throws IOException {
//        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//        if(!captcha.equalsIgnoreCase(kaptcha)){
//            return WebApiResponse.error("验证码不正确");
//        }

        try{
            Subject subject = ShiroUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(accountDto.getAccount(), accountDto.getPassword());
            subject.login(token);
        }catch (UnknownAccountException e) {
            return WebApiResponse.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return WebApiResponse.error("账号或密码不正确");
        }catch (LockedAccountException e) {
            return WebApiResponse.error("账号已被锁定,请联系管理员");
        }catch (AuthenticationException e) {
            return WebApiResponse.error("账户验证失败");
        }

        return WebApiResponse.success();
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroUtils.logout();
        return "redirect:login.html";
    }
}
